package com.tqjc.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.additional.update.impl.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tqjc.entity.StockSteels;
import com.tqjc.mapper.StockSteelsMapper;
import com.tqjc.service.StockSteelsService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
@DS("xianggang")
public class StockSteelsServiceImpl extends ServiceImpl<StockSteelsMapper, StockSteels> implements StockSteelsService {
    @Resource
    private StockSteelsMapper stockSteelsMapper;


    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public StockSteels queryById(Integer id){
        return stockSteelsMapper.selectById(id);
    }

    /**
     * 分页查询
     *
     * @param task 筛选条件
     * @param current 当前页码
     * @param size  每页大小
     * @return
     */
    @Override
    public Page<StockSteels> paginQuery(StockSteels stockSteels, long current, long size){
        //1. 构建动态查询条件
        LambdaQueryWrapper<StockSteels> queryWrapper = new LambdaQueryWrapper<>();
        if(stockSteels.getStockId()!=0){
            queryWrapper.eq(StockSteels::getStockId, stockSteels.getStockId());
        }
        //2. 执行分页查询
        Page<StockSteels> pagin = new Page<>(current , size , true);
        IPage<StockSteels> selectResult = stockSteelsMapper.selectByPage(pagin , queryWrapper);
        pagin.setPages(selectResult.getPages());
        pagin.setTotal(selectResult.getTotal());
        pagin.setRecords(selectResult.getRecords());
        //3. 返回结果
        return pagin;
    }


    @Override
    public StockSteels insert(StockSteels stockSteels){
        stockSteelsMapper.insert(stockSteels);
        return stockSteels;
    }

    @Override
    public StockSteels update(StockSteels stockSteels){

        stockSteelsMapper.update(stockSteels,null);
        //1. 根据条件动态更新
        LambdaUpdateChainWrapper<StockSteels> chainWrapper = new LambdaUpdateChainWrapper<StockSteels>(stockSteelsMapper);
        if(stockSteels.getStockId()!=0){
            chainWrapper.eq(StockSteels::getStockId, stockSteels.getStockId());
        }
        //2. 设置主键，并更新
        chainWrapper.set(StockSteels::getId, stockSteels.getId());
        boolean ret = chainWrapper.update();
        //3. 更新成功了，查询最最对象返回
        if(ret){
            return queryById(stockSteels.getId());
        }else{
            return stockSteels;
        }
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id){
        int total = stockSteelsMapper.deleteById(id);
        return total > 0;
    }
}